package io.renren.common.utils;

import io.renren.common.exception.RRException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author wangyi
 * @createdate 2017/12/20 17:59
 **/
public class FileUtils {

    public static String createfile(MultipartFile mf, String uploadImgPath){//创建文件
        // 取文件名
        String fileName = mf.getOriginalFilename();
        // 取文件后缀
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        String path= System.currentTimeMillis() +"."+ fileType;
        String filePath = uploadImgPath + path;
        try {
            mf.transferTo(new File(filePath));
        }catch (Exception e) {
            e.printStackTrace();
            throw new RRException("图片上传失败");
        }
        return path;
    }


    public static void getImg(String path,HttpServletResponse response) throws Exception{
        File file=new File(path);
        if(file.exists()) {
            response.setContentType("image/jpeg");
            // 创建文件输入流
            FileInputStream is = new FileInputStream(file);
            // 响应输出流
            ServletOutputStream out = response.getOutputStream();
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        }
    }

//    public static boolean deleteFile(String fileName) {
//        File file = new File(fileName);
//        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
//        if (file.exists() && file.isFile()) {
//            if (file.delete()) {
//                System.out.println("删除单个文件" + fileName + "成功！");
//                return true;
//            } else {
//                System.out.println("删除单个文件" + fileName + "失败！");
//                return false;
//            }
//        } else {
//            System.out.println("删除单个文件失败：" + fileName + "不存在！");
//            return false;
//        }
//    }
}
